﻿-- Author      : Thorwald Odin
-- Create Date : 12/7/2013 2:03:13 PM
local _, addon = ...;

LootFilter = addon;

LibStub("AceAddon-3.0"):NewAddon(addon, "LootFilter", "AceEvent-3.0", "AceConsole-3.0");

local L = addon.Locale;

--addon.Locale = LibStub("AceLocale-3.0"):GetLocale("LootFilter", true);

function addon:OnInitialize()
	self:SetupConfig();
	self:SetupLDB();
	self:SetupScheduler();
	self.Locale = LibStub("AceLocale-3.0"):GetLocale("LootFilter");
	self.Version = GetAddOnMetadata("LootFilter", "X-Version");
	
	for _, cmd in pairs(self.SlashCmds) do
		self:RegisterChatCommand(cmd, 'OnCommand');
	end
	
	self.LootStack = {};
	self.ItemStack = {};
	
	self.ItemTypes = {};
	self.ItemSubTypes = {};
	self.ItemQuality = {};
	self.ItemQualityColorBlind = {};
	
	for i, t in pairs({GetAuctionItemClasses()}) do -- build localized item type and item sub type lists
		self.ItemTypes[i] = t;
		self.ItemSubTypes[i] = {};
		for j, u in pairs({GetAuctionItemSubClasses(i)}) do
			self.ItemSubTypes[i][j] = u;
		end
	end
	
	for i = 0, 7 do
		local r, g, b, hex = GetItemQualityColor(i)
		self.ItemQuality[i] = hex .. getglobal('ITEM_QUALITY' .. i .. '_DESC') .. '|r';
		self.ItemQualityColorBlind[i] = getglobal('ITEM_QUALITY' .. i .. '_DESC');
	end
end

function addon:OnEnable()
	for _, event in pairs(self.Events) do
		self:RegisterEvent(event);
	end
end

function addon:OnDisable()
	self:UnregisterAllEvents();
end

addon.SlashCmds = {
	'lf',
	'lootfilter',
};

addon.Events = {
	"LOOT_OPENED",
	"LOOT_CLOSED",
};

function addon:LOOT_OPENED()
	if not self.db.Enabled then
		return;
	end
	self.InLoot = true;
	local num = GetNumLootItems();
	local link;
	for i = 1, num do
		if GetLootSlotType(i) == LOOT_SLOT_ITEM then ---if LootSlotIsItem(i) then
			link = GetLootSlotLink(i);
			if link then
				table.insert(self.LootStack, link);
			end
		end
	end
end

function addon:LOOT_CLOSED()
	if not self.db.Enabled then
		return;
	end
	self:Schedule(self.db.FilterDelay, {Function = self.Filter.Methods[self.db.FilterMode]});
	self.InLoot = false;
end

function addon:OnCommand(msg)
	self:ShowConfig();
end

